package com.ayf.payment.game.api.sms;

import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.entity.platform.SmsChannelConfig;
import com.ayf.payment.game.api.entity.platform.SmsRecord;
import com.ayf.payment.game.api.service.platform.SmsRecordService;
import com.ayf.payment.game.api.type.SMSType;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.RandomStrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Component
public abstract class SMSHandler {

    @Autowired
    private SmsRecordService smsRecordService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    public abstract void send(String phone, SMSType type, SmsChannelConfig SMSConfig, Integer merchantId);

    public void save(SmsRecord smsRecord, SMSType type, String code, Integer merchantId) {
        Date today = new Date();
        smsRecord.setSmsCode(code);
        smsRecord.setSendTime(today);
        smsRecord.setSendDateIndex(DateUtils.dateToInteger(today));
        smsRecord.setSmsType(type.name());
        if (merchantId != null) {
            smsRecord.setMerchantId(merchantId);
        }
        //入库
        redisCacheUtil.setObjectToCache(type.name() + smsRecord.getSendPhone(), code, 60 * 5L, TimeUnit.SECONDS);
        smsRecordService.insert(smsRecord);
    }

    public String getCode() {
        return RandomStrUtils.createRandom(true, 6);
    }
}
